import http from '../static/plugins/axios'
import websocket from '../static/plugins/websocket'
import vue from '../main'
import Vue from 'vue'

let interval = null;
const urls = {
  info: 'public/info',
  dict: 'public/get/dict',
  logout: 'public/logout',
  conf: 'public/conf',
  version: 'public/version'
}

function stop() {
  if (interval == null) {
    return
  }
  clearInterval(interval)
  interval = null
}

function start() {
  stop()
  interval = setInterval(() => {
    http.get(urls.info, null, true, true).then(rsp => {
      if (!rsp) {
        stop()
        vue.$router.push('/login')
      }
    })
  }, 5000)
}

function open(userName) {
  let url = "ws://";
  if (process.env.VUE_APP_BASE_URL) {
    url += process.env.VUE_APP_BASE_URL;
  } else {
    url += window.location.hostname;
    const port = window.location.port;
    if (port != null && port != '') {
      url += (":" + port);
    }
  }
  url = url + "/webSocket/" + userName;
  websocket.init(url, "websockMessage");
}

export default {
  updateState(state, param) {
    state[param.prop] = param.value;
  },

  initSizes(state) {
    const height = window.innerHeight;
    const width = window.innerWidth;
    const loginHeight = 350;
    const loginWidth = 450;
    const navHead = state.showHeader ? 80 : 0;
    const map = {
      medium: 50,
      small: 42,
      mini: 35
    };
    const head = map[state.size] ? map[state.size] : 60;
    const pd = 0;
    const page = 37;
    Vue.set(state.sizes, 'fullHeight', height + 'px');
    Vue.set(state.sizes, 'loginHeight', loginHeight + 'px');
    Vue.set(state.sizes, 'loginWidth', loginWidth + 'px');
    Vue.set(state.sizes, 'loginTop', (height - loginHeight) * 0.4 + 'px');
    Vue.set(state.sizes, 'loginLeft', (width - loginWidth) * 0.49 + 'px');
    Vue.set(state.sizes, 'headHeight', navHead + 'px');
    Vue.set(state.sizes, 'mainHead', head + 'px');
    Vue.set(state.sizes, 'mainHeight', height - navHead + 'px');
    Vue.set(state.sizes, 'tableHei', height - navHead - head - pd);
    Vue.set(state.sizes, 'pTableHei', state.sizes.tableHei - page);
  },

  getUserInfo(state) {
    http.get(urls.info).then(response => {
        if (response) {
          state.userInfo = response;
          state.menuGroups = [{
            name: '主页',
            id: 'home',
            child: []
          }];
          if (response.permission == '1') {
            state.menuGroups.push({
              name: '系统管理',
              id: 'sys',
              child: [{
                name: '配置管理',
                id: 'config'
              }, {
                name: '用户管理',
                id: 'user'
              }]
            })
          }
          start()
          // open(response.userId);
        } else {
          vue.$router.push('/login')
        }
      })
      .catch(() => {
        vue.$router.push('/login')
      })
  },

  websockMessage(state, data) {
    const handler = state.handlers[data.type];
    if (handler != null) {
      handler(data.data);
    }
  },

  getCfg(state) {
    http.get(urls.conf).then(rsp => {
      state.conf = rsp;
    });
    http.get(urls.version).then(rsp => {
      state.version = rsp;
    });
  },

  getDictMap(state, codes, callBack) {
    if (codes == null) {
      return
    }
    const arr = []
    for (let i = 0; i < codes.length; i++) {
      if (Object.keys(state.dict).indexOf(codes[i]) == -1) {
        arr.push(codes[i])
      }
    }
    if (arr.length == 0) {
      return
    }
    http.post(urls.dict, arr).then(function(response) {
      if (response) {
        for (let i = 0; i < arr.length; i++) {
          const key = arr[i]
          state.dict[key] = {}
          const dicts = response[key]
          if (dicts == null) {
            continue
          }
          for (let j = 0; j < dicts.length; j++) {
            const tmp = dicts[j]
            const num = parseInt(tmp.code)
            if (!isNaN(num)) {
              state.dict[key][num] = tmp.name
            } else {
              state.dict[key][tmp.code] = tmp.name
            }
          }
        }
        if (callBack != null) {
          callBack()
        }
      }
    })
  },

  logout(state) {
    http.get(urls.logout).then(response => {
      if (response) {
        vue.$router.push('/login')
        state.userInfo = {}
      }
    });
    websocket.close();
  }

}
